package com.hzncc.flowable_diboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.binding.QueryBuilder;
import com.diboot.core.entity.Dictionary;
import com.diboot.core.service.DictionaryService;
import com.diboot.core.service.impl.BaseServiceImpl;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.S;
import com.diboot.core.util.SqlExecutor;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.iam.entity.IamUser;
import com.diboot.iam.service.IamUserService;
import com.diboot.iam.service.SystemConfigService;
import com.diboot.iam.util.IamSecurityUtils;
import com.diboot.notification.config.Cons;
import com.diboot.notification.entity.Message;
import com.hzncc.flowable_diboot.dto.CustomConnectorDTO;
import com.hzncc.flowable_diboot.dto.CustomerDTO;
import com.hzncc.flowable_diboot.dto.CustomerPortraitDTO;
import com.hzncc.flowable_diboot.dto.SalesTeamDTO;
import com.hzncc.flowable_diboot.entity.*;
import com.hzncc.flowable_diboot.entity.customer_manage.InternationalCustomerArea;
import com.hzncc.flowable_diboot.excel.model.CustomerOldCrmImportModel;
import com.hzncc.flowable_diboot.mapper.CustomerMapper;
import com.hzncc.flowable_diboot.mapper.CustomerPortraitMapper;
import com.hzncc.flowable_diboot.mapper.StarCustomMapper;
import com.hzncc.flowable_diboot.mapper.customer_manage.InternationalCustomerAreaMapper;
import com.hzncc.flowable_diboot.rabbitmq.service.impl.SendMessageService;
import com.hzncc.flowable_diboot.service.*;
import com.hzncc.flowable_diboot.util.ConstantUtil;
import com.hzncc.flowable_diboot.util.MessageCons;
import com.hzncc.flowable_diboot.vo.CustomerDetailVO;
import com.hzncc.flowable_diboot.vo.CustomerListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 客户 相关Service实现类
 *
 * @author MyName
 * @version 1.0
 * @date 2024-05-15
 * Copyright © MyCorp
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerServiceImpl extends BaseServiceImpl<CustomerMapper, Customer> implements CustomerService {

    private final StarCustomMapper starCustomMapper;

    private final StarCustomService starCustomService;

    private final SendMessageService sendMessageService;

    private final SalesTeamService salesTeamService;

    private final IamUserService iamUserService;

    private final CustomerPortraitService customerPortraitService;

    private final CustomerTransSeaRecordService customerTransSeaRecordService;

    private final CustomConnectorService customConnectorService;

    private final CommonService commonService;

    private final SystemConfigService systemConfigService;

    private final CustomerMapper customerMapper;

    private final ToDoListService toDoListService;

    private final PersonChangeRecordService personChangeRecordService;

    private final CustomerPortraitMapper customerPortraitMapper;

    private final DictionaryService dictionaryService;

    private final TianYanChaService tianYanChaService;

    private final InternationalCustomerAreaMapper internationalCustomerAreaMapper;

    /**
     * 客户查询
     *
     * @param queryDto   查询条件
     * @param pagination 分页信息
     * @param type       查询分类 self - 我的客户 star - 关注客户 resp - 负责的客户  sub - 下属客户
     * @return
     */
    @Override
    public JsonResult<List<CustomerListVO>> selectCustom(CustomerDTO queryDto, Pagination pagination, String type) {
        QueryWrapper<CustomConnectorDTO> queryWrapper = QueryBuilder.toQueryWrapper(queryDto);
        if (pagination != null && V.isEmpty(pagination.getOrderBy())) {
            pagination.setOrderBy(Pagination.ORDER_BY_ID_DESC);
        }
        // 当前登录用户
        IamUser currentUser = iamUserService.getEntity(IamSecurityUtils.getCurrentUserId());
        if (!commonService.isCrossTenant(IamSecurityUtils.getCurrentTenantId())) {
            if ("resp".equals(type)) {
                queryWrapper.eq("principal", currentUser.getId());
            }
            List<String> plist = new ArrayList<>();
            List<String> cids = new ArrayList<>();
            if ("sub".equals(type) || "self".equals(type)) {
                // 下属客户查询
                List<String> uids = commonService.findSubEmp(currentUser);
                if (uids.isEmpty() && "sub".equals(type)) {
                    return JsonResult.OK(new ArrayList<>());
                } else if (!uids.isEmpty()) {
                    // 查询下属所属销售团队
                    QueryWrapper w = QueryBuilder.toQueryWrapper(new SalesTeamDTO());
                    w.in("member", uids);
                    List<SalesTeam> teams = salesTeamService.getEntityList(w);
                    List<String> customerIds = BeanUtils.collectToList(teams, SalesTeam::getCustomerId);
                    if ("self".equals(type)) {
                        plist.addAll(uids);
                        if (customerIds != null && !customerIds.isEmpty()) {
                            cids.addAll(customerIds);
                        }
                    } else {
                        queryWrapper.and(qw -> {
                            qw.in("principal", uids);
                            if (!customerIds.isEmpty()) {
                                qw.or().in("id", customerIds);
                            }
                        });
                    }
                }
            }
            // 获取全部客户
            if ("self".equals(type)) {
                // 本人所处的销售团队
                List<SalesTeam> teams = salesTeamService.getEntityList(QueryBuilder.toQueryWrapper(new SalesTeamDTO().setMember(currentUser.getId())));
                // 团队负责人
                List<String> customerIds = teams.stream().map(SalesTeam::getCustomerId).distinct().collect(Collectors.toList());
                plist.add(currentUser.getId());
                // 查询条件分级
                if (customerIds.isEmpty()) {
                    queryWrapper.and(wrapper -> wrapper.in("principal", plist));
                } else {
                    cids.addAll(customerIds);
                    queryWrapper.and(wrapper -> {
                        wrapper.in("principal", plist)
                                .or()
                                .in("id", cids);
                    });
                }
            }
            // 获取我关注的客户
            if ("star".equals(type)) {
                //List<CustomerListVO> customerListVOS = baseMapper.selectStarCustom(currentUser.getId(), queryDto.getName());
                List<String> ids = customerMapper.selectStarCustomerId(currentUser.getId());
                if (ids != null && !ids.isEmpty()) {
                    queryWrapper.in("id", ids);
                } else {
                    return JsonResult.OK();
                }
            }
        }
        List<CustomerListVO> viewObjectList = getViewObjectList(queryWrapper, pagination, CustomerListVO.class);
        if (!viewObjectList.isEmpty()) {
            // 查询用户是否关注客户
            QueryWrapper<StarCustom> qw = new QueryWrapper();
            qw.eq("user_id", currentUser.getId());
            qw.in("custom_id", viewObjectList.stream().map(CustomerListVO::getId).toArray());
            List<StarCustom> starCustoms = starCustomMapper.selectList(qw);
            Set<String> customIdSet = starCustoms.stream().map(StarCustom::getCustomId).collect(Collectors.toSet());
            viewObjectList.forEach(e -> {
                e.setIsStar(customIdSet.contains(e.getId()));
            });
        }
        return JsonResult.OK(viewObjectList).bindPagination(pagination);
    }


    /**
     * 客户转移
     *
     * @param uid 目标id
     * @param ids 客户id
     * @return
     */
    @Override
    public JsonResult<?> trans(String uid, List<String> ids) {
        if (Objects.equals(IamSecurityUtils.getCurrentUserId(), uid)) {
            return JsonResult.FAIL_INVALID_PARAM("不能变更负责人给本人！");
        }
        List<Customer> customerList = this.getEntityListByIds(ids);
        List<Customer> customers = new ArrayList<>();
        List<SalesTeam> salesTeams = new ArrayList<>();
        List<PersonChangeRecord> records = new ArrayList<>();
        for (Customer cus : customerList) {
            PersonChangeRecord record = new PersonChangeRecord();
            record.setCustomerId(cus.getId());
            record.setOperator(IamSecurityUtils.getCurrentUserId());
            record.setOrigin(cus.getPrincipal());
            record.setTarget(uid);
            record.setOper("1"); // 1 转移 0 分配
            records.add(record);
            String oldUid = cus.getPrincipal();
            cus.setPrincipal(uid);
            customers.add(cus);
            // 销售团队处置
            List<SalesTeam> entityList = salesTeamService.getEntityList(QueryBuilder
                    .toQueryWrapper(new SalesTeamDTO()
                            .setCustomerId(cus.getId())));
            entityList.forEach(e -> {
                e.setManagerId(uid);
                // 避免重复
                if (Objects.equals(uid, e.getMember())) {
                    e.setDeleted(true);
                }
                // 变更管理
                if (Objects.equals(oldUid, e.getMember())) {
                    e.setMember(uid);
                }
            });
            salesTeams.addAll(entityList);
        }
        this.updateEntities(customers);
        personChangeRecordService.createEntities(records);
        salesTeamService.updateEntities(salesTeams);
        // 清除关注
        QueryWrapper<StarCustom> qw = new QueryWrapper<>();
        qw.eq("user_id", IamSecurityUtils.getCurrentUserId()).in("custom_id", ids);
        List<StarCustom> stars = starCustomService.getEntityList(qw);
        starCustomService.deleteEntities(stars);
        // 发送消息
        IamUser currentUser = IamSecurityUtils.getCurrentUser();
        List<String> names = customers.stream().map(Customer::getName).collect(Collectors.toList());
        sendMessageService.sendRetainedMessage(new Message().setTitle("客户转移").setSender(currentUser.getId())
                .setReceiver(uid).setAppModule(ConstantUtil.MODEL_CUSTOMER)
                .setContent(String.format(ConstantUtil.CUSTOMER_TRANSACTION_MSG_TEMPLATE, currentUser.getRealname(), S.join(names)))
                .setTemplateId("").setBusinessCode("").setBusinessType("").setChannel(Cons.MESSAGE_CHANNEL.SYS_MSG.name())
                .setStatus(Cons.MESSAGE_STATUS.PENDING.name()));
        return JsonResult.OK();
    }

    /**
     * 公海转移
     *
     * @param cusId 客户id
     * @param sea   租户id
     */
    @Override
    public void transSea(String cusId, String sea) {
        // 权限控制
        Customer cus = this.getEntity(cusId);
        cus.setTenantId(sea);
        // 生成转移记录
        CustomerTransSeaRecord record = new CustomerTransSeaRecord()
                .setCustomerId(cusId)
                .setCustomerName(cus.getName())
                .setTransTime(LocalDateTime.now())
                .setOrigin(IamSecurityUtils.getCurrentTenantId())
                .setTarget(sea);
        customerTransSeaRecordService.createEntity(record);
        this.updateEntity(cus);
    }

    /**
     * 分配
     *
     * @param cusId
     * @param uid
     */
    @Override
    public void distribute(String cusId, String uid) {
        Customer customer = this.getEntity(cusId);
        customer.setPrincipal(uid); // 设置负责人
        customer.setIsEnter(1); // 移除公海
        customer.setLastFollwUpTime(LocalDateTime.now()); // 更新跟进时间避免短时间内再次移入公海
        BigDecimal val = systemConfigService.findConfigValue(ConstantUtil.VALID, ConstantUtil.VALID_CUSTOMER);
        customer.setExpirationTime(val.toString());
        // 初始化客户画像
        List<CustomerPortrait> entityList = customerPortraitService.getEntityList(QueryBuilder.toQueryWrapper(new CustomerPortraitDTO().setCustomerId(cusId)));
        // 没有画像
        if (entityList.isEmpty()) {
            customerPortraitService.createEntity(new CustomerPortrait().setCustomerId(cusId));
        }
        updateEntity(customer);
        PersonChangeRecord record = new PersonChangeRecord();
        record.setOperator(IamSecurityUtils.getCurrentUserId());
        record.setOper("0"); // 0 分配 1 转移
        record.setOrigin("");
        record.setTarget(uid);
        personChangeRecordService.createEntity(record);
        // 添加到团队
        SalesTeam salesTeam = new SalesTeam();
        salesTeam.setCustomerId(cusId);
        salesTeam.setMember(uid);
        salesTeamService.createEntity(salesTeam);
        IamUser user = IamSecurityUtils.getCurrentUser();
        // 发送分配消息
        sendMessageService.sendRetainedMessage(new Message().setChannel(Cons.MESSAGE_CHANNEL.SYS_MSG.name())
                .setTitle(MessageCons.CUS_DIS_TITLE)
                .setReceiver(uid).setSender(IamSecurityUtils.getCurrentUserId())
                .setContent(String.format(ConstantUtil.CUSTOMER_DIS_MSG_TEMPLATE, user.getRealname(), customer.getName()))
                .setStatus(Cons.MESSAGE_STATUS.DELIVERY.name()).setAppModule(ConstantUtil.MODEL_CUSTOMER).setTemplateId("")
                .setBusinessCode(MessageCons.CUS_DIS_BUS_CODE).setBusinessType(MessageCons.CUS_DIS_BUS_TYPE)
                .setChannel(Cons.MESSAGE_CHANNEL.SYS_MSG.name()));
        // 待办列表
        toDoListService.createToDo(new ToDoList()
                .setCustomer(cusId)
                .setExecutor(uid)
                .setModel(ConstantUtil.MODEL_CUSTOMER)
                //.setMission(String.format(ConstantUtil.CUSTOMER_DIS_MSG_TEMPLATE,((IamUser)IamSecurityUtils.getCurrentUser()).getRealname(),customer.getName()))
                .setDisTime(LocalDateTime.now())
                .setHasMsg(true)
                .setType(ConstantUtil.DIS_CUSTOMER));
    }

    /**
     * 客户详情
     *
     * @param id
     * @return
     */
    @Override
    public CustomerDetailVO getDetail(String id) {
        CustomerDetailVO viewObject = this.getViewObject(id, CustomerDetailVO.class);
        List<CustomConnector> entityList = customConnectorService.getEntityList(QueryBuilder.toQueryWrapper(new CustomConnectorDTO().setCustomerId(id)));
        if (!entityList.isEmpty()) {
            CustomConnector customConnector = entityList.get(0);
            viewObject.setConnector(customConnector.getConnector());
            viewObject.setConnectorWay(customConnector.getConnectWay());
        }
        return viewObject;
    }

    @Override
    public JsonResult<?> createCustomer(Customer customer) {
        String creditCode = customer.getCreditCode();
        String name = customer.getName();
        QueryWrapper<Customer> qw = new QueryWrapper<>();
        qw.eq("credit_code", creditCode).or().eq("name", name);
        Customer entity = this.getSingleEntity(qw);
        // 客户已存在
        if (entity != null) {
            IamUser user = iamUserService.getEntity(entity.getPrincipal());
            if (user == null) {
                return JsonResult.FAIL_INVALID_PARAM(name + "客户已存在，已进入客户公海");
            }
            return JsonResult.FAIL_INVALID_PARAM(name + "客户已存在，负责人为" + user.getRealname());
        }
        JsonResult<?> jsonResult = validCustomer(customer);
        if (jsonResult.getCode() != 0){
            return jsonResult;
        }
        BigDecimal enterThreshold = systemConfigService.findConfigValue(ConstantUtil.VALID, ConstantUtil.VALID_CUSTOMER);
        // 默认为十五天
        if (enterThreshold == null) {
            enterThreshold = new BigDecimal("15");
        }
        customer.setExpirationTime(enterThreshold.toString()); // 初始化过期天数
        if (customer.getIsEnter() == 0) {
            customer.setPrincipal(null);
        }
        boolean success = this.createEntity(customer);
        log.debug("新建数据 客户:{} {}", customer.getId(), success ? "成功" : "失败");
        if (success) {
            // 创建空白客户画像
            customerPortraitService.createEntity(new CustomerPortrait().setCustomerId(customer.getId()));
            // 初始化销售团队
            if (S.isNotBlank(customer.getPrincipal())) {
                salesTeamService.createEntity(new SalesTeam()
                        .setCustomerId(customer.getId())
                        //.setManagerId(customer.getPrincipal())
                        .setMember(customer.getPrincipal()));
            }
        }
        return JsonResult.OK();
    }

    private JsonResult<?> validCustomer(Customer customer) {
        QueryWrapper<Customer> qw = new QueryWrapper<>();
        qw.lambda().eq(Customer::getEmail, customer.getEmail());
        long count = this.count(qw);
        if (count > 0){
            return JsonResult.FAIL_INVALID_PARAM("邮箱已存在");
        }
        qw.clear();
        qw.lambda().eq(Customer::getInternationalCustomerCompany, customer.getInternationalCustomerCompany());
        long count1 = this.count(qw);
        if (count1 > 0){
            return JsonResult.FAIL_INVALID_PARAM("公司名称已存在");
        }
        qw.clear();
        qw.lambda().eq(Customer::getPhoneNumber, customer.getPhoneNumber());
        long count2 = this.count(qw);
        if (count2 > 0){
            return JsonResult.FAIL_INVALID_PARAM("手机号已存在");
        }
        qw.clear();
        qw.lambda().eq(Customer::getWebUrl, customer.getWebUrl());
        long count3 = this.count(qw);
        if (count3 > 0){
            return JsonResult.FAIL_INVALID_PARAM("网址已存在");
        }
        return JsonResult.OK();
    }


    /**
     * 进入公海检查
     *
     * @author 陈广煜
     * @date 2024/5/21
     */
    public void checkFollowTime() throws Exception {
        String exp = "select * from mdl_customer where expiration_time = 0 and is_deleted = 0 and is_enter = 1";
        List<Customer> customers = SqlExecutor.getJdbcTemplate().query(exp, BeanPropertyRowMapper.newInstance(Customer.class));
        //baseMapper.updateExpire(); // 更新据进入公海天数
        String sql = "update mdl_customer set expiration_time = expiration_time - 1 where is_deleted = 0 and expiration_time > 0";
        SqlExecutor.executeUpdate(sql);
        String enterDays = "update mdl_customer set enter_days = enter_days + 1 where is_enter = 0 and is_deleted = 0";
        SqlExecutor.executeUpdate(enterDays);
        if (customers.isEmpty()) {
            return;
        }
        customers.forEach(e -> {
            e.setIsEnter(0);
            e.setEnterTime(LocalDateTime.now());
            e.setEnterReason("长时间未跟进，系统自动置入公海");
            e.setPrincipal(null);
        });
        List<String> ids = BeanUtils.collectToList(customers, Customer::getId);
        String updateCus = "update mdl_customer set is_enter = 0,enter_time = now(),enter_reason='长时间未跟进，系统自动置入公海',principal=null where id in ('" + String.join("','", ids) + "')";
        SqlExecutor.executeUpdate(updateCus);
        String updateTeam = "update mdl_sales_team set is_deleted = 1 where customer_id in ('" + String.join("','", ids) + "')";
        SqlExecutor.executeUpdate(updateTeam);
    }

    /**
     * 导入客户
     *
     * @param list
     * @return
     */
    @Override
    public Set<String> convertAndSave(List<CustomerOldCrmImportModel> list) throws InterruptedException {
        long start = System.currentTimeMillis();
        // 去除list中客户名称相同的客户
        Set<String> existingCustomerNames = new HashSet<>();
        List<CustomerOldCrmImportModel> uniqueList = new ArrayList<>();
        for (CustomerOldCrmImportModel customerOldCrmImportModel : list) {
            if (!existingCustomerNames.contains(customerOldCrmImportModel.getCustomerName())) {
                uniqueList.add(customerOldCrmImportModel);
            }
            existingCustomerNames.add(customerOldCrmImportModel.getCustomerName());
        }
        String currentUserId = getCurrentUserId();
        List<Customer> newCustomers = new ArrayList<>();
        List<CustomerPortrait> newCustomerPortraits = new ArrayList<>();
        List<SalesTeam> newSalesTeamMembers = new ArrayList<>();
        Map<String, Customer> existingCustomersMap = new HashMap<>();
        List<String> existingCustomerIds = new ArrayList<>();

        // 预先查询所有客户名称，避免在循环内查询
        List<Customer> existingCustomers = customerMapper.selectList(new QueryWrapper<Customer>().in("name", uniqueList.stream().map(CustomerOldCrmImportModel::getCustomerName).collect(Collectors.toList())));
        for (Customer customer : existingCustomers) {
            existingCustomersMap.put(customer.getName(), customer);
            existingCustomerIds.add(customer.getId());
        }

        // 预先查询所有销售团队成员，避免在循环内查询
        List<SalesTeam> existingSalesTeamMembers = new ArrayList<>();
        if (!existingCustomerIds.isEmpty()) {
            existingSalesTeamMembers = salesTeamService.getEntityList(new QueryWrapper<SalesTeam>().in("customer_id", existingCustomerIds).eq("member", currentUserId));
        }
        Set<String> existingSalesTeamCustomerIds = existingSalesTeamMembers.stream().map(SalesTeam::getCustomerId).collect(Collectors.toSet());

        // 预先查询用户信息，避免在循环内查询
        List<IamUser> existingUsers = iamUserService.getEntityList(new QueryWrapper<IamUser>());
        Map<String, String> existingUserMap = existingUsers.stream().collect(Collectors.toMap(IamUser::getRealname, IamUser::getId));

        // 预查询数据字典
        List<Dictionary> entityList = dictionaryService.getEntityList(new QueryWrapper<>().in("type", Arrays.asList("city", "province")));
        Map<String, String> dicMap = new HashMap<>();
        for (Dictionary dic : entityList) {
            dicMap.put(dic.getType() + dic.getItemName(), dic.getItemValue());
        }

        // 预查客户大区
        List<InternationalCustomerArea> internationalCustomerAreas = internationalCustomerAreaMapper.selectList(new QueryWrapper<>());
        Map<String, String> areaMap = new HashMap<>();
        for (InternationalCustomerArea internationalCustomerArea : internationalCustomerAreas) {
            areaMap.put(internationalCustomerArea.getCountryRegion()+internationalCustomerArea.getMajorArea()+internationalCustomerArea.getAreaDivision(), internationalCustomerArea.getId());
        }

        List<SalesTeam> newCustomerSalesTeams = new ArrayList<>();
        for (CustomerOldCrmImportModel importModel : uniqueList) {
            if (importModel.getCustomerName() == null) {
                continue;
            }
            Customer existingCustomer = existingCustomersMap.get(importModel.getCustomerName());
            if (existingCustomer != null) {
                // 客户名称重复，将当前登录用户加入到客户的销售团队
                if (!existingSalesTeamCustomerIds.contains(existingCustomer.getId())) {
                    SalesTeam salesTeam = new SalesTeam()
                            .setCustomerId(existingCustomer.getId())
                            .setMember(currentUserId)
                            .setRole("normal");
                    newSalesTeamMembers.add(salesTeam);
                }
            } else {
                Customer newCustomer = new Customer();
                BeanUtil.copyProperties(importModel, newCustomer);
                newCustomer.setCreateBy(existingUserMap.get(importModel.getCreateBy()));
                // 客户名称唯一，创建新客户
                newCustomer
                        .setName(importModel.getCustomerName())
                        .setAddress(importModel.getAddress())
                        .setSn(importModel.getSapNo())
                        .setPrincipal(existingUserMap.get(importModel.getPersonInCharge() == null ? importModel.getCreateBy() : importModel.getPersonInCharge()))
                        .setCreditCode(importModel.getUnifiedCreditCode())
                        .setCity(dicMap.get("city" + importModel.getCity()))
                        .setInternationalCustomerArea(areaMap.get(importModel.getInternationalCustomerArea()+importModel.getMajorArea()+importModel.getAreaDivision()))
                        .setProvince(dicMap.get("province" + importModel.getProvinces()));
                newCustomer.setIsEnter(newCustomer.getPrincipal() != null ? 1 : 0);
                newCustomers.add(newCustomer);
                if (newCustomer.getPrincipal() == null && importModel.getCreateBy() != null) {
                    newCustomer.setPrincipal(existingUserMap.get(importModel.getCreateBy()));
                }
                if (newCustomer.getInternationalCustomerArea() == null) {
                    // 创建国际客户大区
                    InternationalCustomerArea area = new InternationalCustomerArea();
                    area.setMajorArea(importModel.getMajorArea());
                    area.setAreaDivision(importModel.getAreaDivision());
                    area.setCountryRegion(importModel.getInternationalCustomerArea());
                    internationalCustomerAreaMapper.insert(area);
                    newCustomer.setInternationalCustomerArea(area.getId());
                    areaMap.put(importModel.getInternationalCustomerArea()+importModel.getMajorArea()+importModel.getAreaDivision(), area.getId());
                }


                // 创建客户画像
                CustomerPortrait customerPortrait = new CustomerPortrait()
                        .setCustomerId(newCustomer.getName())
                        .setMainSys(importModel.getMainSystem())
                        .setCompetitor(importModel.getCompetitors())
                        .setMainBusinessDes2(importModel.getCustomerMainBusinessDescription())
                        .setCoreReason(importModel.getSupportingCoreFactors())
                        .setBreakthrough(importModel.getCustomerCooperationDirectionAnalysis());
                newCustomerPortraits.add(customerPortrait);

                // 创建销售团队
                SalesTeam newSalesTeam = new SalesTeam()
                        .setCustomerId(newCustomer.getName())
                        .setMember(newCustomer.getPrincipal())
                        .setRole("normal");
                if (S.isNotBlank(importModel.getSalesStaffQuery()) && !S.equals(importModel.getSalesStaffQuery(),importModel.getCreateBy())) {
                    SalesTeam salesTeam = new SalesTeam()
                            .setCustomerId(newCustomer.getName())
                            .setMember(existingUserMap.get(importModel.getSalesStaffQuery()))
                            .setRole("normal");
                    newCustomerSalesTeams.add(salesTeam);
                }
                newCustomerSalesTeams.add(newSalesTeam);
            }
        }
        long step1 = System.currentTimeMillis();
        log.info("处理excel数据耗时:{}", step1 - start);
        Set<String> errorCustomers = new HashSet<>();
        // 收集统一信用代码为空的客户
        if (!S.equals(IamSecurityUtils.getCurrentTenantId(), "1867464222370451458")) {
            List<Customer> customers = newCustomers.stream().filter(customer -> customer.getCreditCode() == null).toList();
            for (Customer customer : customers) {
                JsonResult<?> detail = tianYanChaService.detail(customer.getName());
                if (detail.getCode() == 0) {
                    Map<String, String> data = (Map<String, String>) detail.getData();
                    customer.setCreditCode(data.get("creditCode"));
                    customer.setTaxNumber(data.get("taxNumber"));
                } else {
                    errorCustomers.add(customer.getName());
                }
                // 避免请求太快，避免被封
                Thread.sleep(100);
            }
            // 批量插入新客户
            newCustomers = newCustomers.stream().filter(customer -> !errorCustomers.contains(customer.getName())).toList();
        }
        long step2 = System.currentTimeMillis();
        log.info("天眼查耗时:{}", step2 - step1);
        if (!newCustomers.isEmpty()) {
            customerMapper.insert(newCustomers);
        }
        long step3 = System.currentTimeMillis();
        log.info("插入新客户耗时:{}", step3 - step2);

        Map<String, String> customerMap = newCustomers.stream().collect(Collectors.toMap(Customer::getName, Customer::getId));
        // 批量插入新客户画像
        if (!newCustomerPortraits.isEmpty()) {
            for (CustomerPortrait newCustomerPortrait : newCustomerPortraits) {
                newCustomerPortrait.setCustomerId(customerMap.get(newCustomerPortrait.getCustomerId()));
            }
            customerPortraitMapper.insert(newCustomerPortraits);
        }
        long step4 = System.currentTimeMillis();
        log.info("插入新客户画像耗时:{}", step4 - step3);

        // 批量插入新销售团队成员
        if (!newSalesTeamMembers.isEmpty()) {
            salesTeamService.createEntities(newSalesTeamMembers);
        }
        long step5 = System.currentTimeMillis();
        log.info("插入新销售团队成员耗时:{}", step5 - step4);

        // 批量插入新销售团队
        if (!newCustomerSalesTeams.isEmpty()) {
            for (SalesTeam newCustomerSalesTeam : newCustomerSalesTeams) {
                newCustomerSalesTeam.setCustomerId(customerMap.get(newCustomerSalesTeam.getCustomerId()));
            }
            salesTeamService.createEntities(newCustomerSalesTeams);
        }
        long step6 = System.currentTimeMillis();
        log.info("插入新销售团队耗时:{}", step6 - step5);
        return errorCustomers;
    }

    private String getCurrentUserId() {
        return IamSecurityUtils.getCurrentUserId();
    }

    @Override
    public Boolean validateUnique(String field, String value) {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(field, value);
        long count = this.count(queryWrapper);
        return count == 0;
    }
}